package process

import (
	"context"
	"gitee.com/alex_li/ad-analysis/internal/db"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/go-log"
	"strings"
	"time"
)

var (
	Verbose = false
)

// 统计单词数

func CountWords(ctx context.Context) (err error) {
	go func() {
		Run(ctx, countWords)
	}()

	return
}

func Run(ctx context.Context, h func() error) {
	for {
		select {
		case <-ctx.Done():
			return
		default:
			err := h()
			if err != nil {
				log.Info(err)
			}
		}
	}
}

func countWords() (err error) {
	log.Info("统计数量")
	var n = 0
	err = app.GetOrm().Transaction(func(c persistence.TxContext) (e error) {
		var list []db.ProductKeys
		_, e = c.Context.QueryTable(new(db.ProductKeys)).
			Filter("WordsCount__isnull", true).
			Limit(100).
			All(&list)
		if e != nil {
			log.Info(e)
			return
		}
		for _, v := range list {
			n++
			words := strings.Split(v.SearchWord, " ")
			v.WordsCount = len(words)

			_, e = c.Context.Update(&v)
			if e != nil {
				log.Info(e)
				return
			}
			if Verbose {
				log.Info("[%d]%s", v.WordsCount, v.SearchWord)
				time.Sleep(time.Millisecond * 300)
			}
		}
		return
	})
	log.Info("本次处理%d个数据", n)
	if n <= 0 {
		log.Info("没有数据需要处理, 休眠30s")
		time.Sleep(time.Second * 30)
	}
	return
}
